﻿using Microsoft.EntityFrameworkCore;
using NewRetail.Application.Components.Warehouse.Entity;
using System;
using System.Linq;
using System.Threading.Tasks;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;

namespace NewRetail.Application.Components.Warehouse
{
    public interface IChangeWarehouseService : IApplicationService
    {
        Task<ChangeWarehouse[]> AttachWarehouseInfo(ChangeWarehouse[] data);
    }

    public class ChangeWarehouseService : MyApplicationService, IChangeWarehouseService
    {
        private readonly IRepository<ChangeWarehouse> changeWarehouses;

        public ChangeWarehouseService(IRepository<ChangeWarehouse> changeWarehouses)
        {
            this.changeWarehouses = changeWarehouses;
        }

        public async Task<ChangeWarehouse[]> AttachWarehouseInfo(ChangeWarehouse[] data)
        {
            if (!data.Any())
            {
                return data;
            }

            var ids = data.SelectMany(x => new[] { x.inWarehouseID, x.outWarehouseID }).ToArray();

            var db = await this.changeWarehouses.GetDbContextAsync();

            var list = await db.Set<Warehouse.Entity.Warehouse>().AsNoTracking()
                .Where(x => ids.Contains(x.Id)).ToArrayAsync();

            foreach (var m in data)
            {
                m.InWarehouse = list.FirstOrDefault(x => x.Id == m.inWarehouseID);
                m.OutWarehouse = list.FirstOrDefault(x => x.Id == m.outWarehouseID);
            }

            return data;
        }

    }
}
